using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Identity.Application.ApiPermissionBindings.Commands;
using Identity.Application.Contracts.Common;
using Identity.Application.PermissionKeyResourceIds.CommandHandlers;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Domain.ValueObjects;
using MediatR;

namespace Identity.Application.ApiPermissionBindings.CommandHandlers
{
    public class ChangeApiPermissionScopeCommandHandler : IRequestHandler<ChangeApiPermissionScopeCommand, Result>
    {
        private readonly IApiPermissionBindingRepository  _apiPermissionBindingRepository;
        private readonly IUnitOfWork _unitOfWork;
        public ChangeApiPermissionScopeCommandHandler(IApiPermissionBindingRepository apiPermissionBindingRepository, IUnitOfWork unitOfWork)
        {
            _apiPermissionBindingRepository = apiPermissionBindingRepository;
            _unitOfWork = unitOfWork;

        }
        public async Task<Result> Handle(ChangeApiPermissionScopeCommand request, CancellationToken cancellationToken)
        {
            var apiPermission = _apiPermissionBindingRepository.GetByResourceId(request.resourceId);
            if (apiPermission == null) return Result.Failure($"无法找到接口资源Id为{request.resourceId} 的接口权限绑定记录");

            var permissionScope = PermissionScope.From(request.PermissionScopeValue);
            if (permissionScope == null) return Result.Failure($"{request.PermissionScopeValue} 为无效认证方式");

            apiPermission.ChangePermissionScope(permissionScope);

            await _unitOfWork.SaveChangesAsync(cancellationToken);

            return Result.Success(apiPermission);
            
        }
    }
}